import redis.clients.jedis.Jedis;
import utils.CleanSessionsThread;

import java.util.UUID;

public class Chapter02 {

    public static void main(String[] args) throws InterruptedException {
        new Chapter02().run();
    }

    private void run() throws InterruptedException {
        Jedis conn = new Jedis("192.168.179.21", 6379);
        conn.select(15);

        testLoginCookies(conn);
    }

    /**
     *
     * @param conn
     */
    private void testLoginCookies(Jedis conn) throws InterruptedException {
        System.out.println("==============testLoginCookies================");
        String token = UUID.randomUUID().toString();
        updateToken(conn,token,"username","itemX");
        System.out.println("We just logged-in/updated token: " + token);
        System.out.println("For user: 'username'");
        System.out.println();

        System.out.println("What username do we get when we look-up that token?");
        String r = checkToken(conn, token);
        System.out.println(r);
        System.out.println();


        System.out.println("Let's drop the maximum number of cookies to 0 to clean them out");
        System.out.println("We will start a thread to do the cleaning, while we stop it later");

        CleanSessionsThread thread = new CleanSessionsThread(0);
        thread.start();
        Thread.sleep(1000);
        thread.quit();
        Thread.sleep(2000);
        if (thread.isAlive()){
            throw new RuntimeException("The clean sessions thread is still alive?!?");
        }

        long s= conn.hlen("login:");
        System.out.println("The current number of sessions still available is: " + s);
    }

    public String checkToken(Jedis conn, String token) {
        return conn.hget("login:", token);
    }

    private void updateToken(Jedis conn, String token, String username, String itemX) {
        long timestamp = System.currentTimeMillis()/ 1000;
        conn.hset("login:",token,username);
        conn.zadd("recent:",timestamp,token);
        if (itemX !=null){
            conn.zadd("viewed:"+token,timestamp,itemX);
            //删除排序集中 key 上排序在 start 和 end 之间的所有元素
            conn.zremrangeByRank("viewed:"+token,0,26);
            conn.zincrby("viewed:",-1,itemX);
        }
    }
}
